<?php
/**
 * @Author:      lyt
 * @DateTime:  2017-05-26 16:55:19
 * @Description: 用于清理应收收回的 逻辑
 */
$api_service_path = __DIR__ . "/../../../../api/";
ob_start();
require_once($api_service_path . "public/index.php");
ob_end_clean();
DB::connection()->disableQueryLog(); 

//预制原来的期初
$bak_ba=DB::select("SELECT * FROM `begin_arrear_bak` ");
foreach ($bak_ba as $_bba) {
	$tran_no = date('Ymd',time()).Common::generateCode(); 
	$ba=new BeginArrear;
    $ba->shop_id=$_bba->shop_id;
    $ba->company_id=$_bba->company_id;
    $ba->current_amount=$_bba->amount;
    $ba->amount=$_bba->amount;
    $ba->created_by=$_bba->created_by;
    $ba->save();
    Account::record($_bba->company_id,0,3,$tran_no,2,218,$_bba->amount,'期初预制欠款,欠款单号:'.$ba->id);
}

$receivable_arr=DB::select("SELECT * FROM `receivable` where verify_status=1 ");
//循环处理收回 没有洗车单不需要处理订单相关
foreach($receivable_arr as $receivable){
	DB::transaction(function () use ($receivable) {
        $receivable= Receivable::where("receivable_id",$receivable->receivable_id)->lockForUpdate()->first();    
        $tran_no = date('Ymd',time()).Common::generateCode();       
        $user = Users::find($receivable->company_id);
        $order_amount=$receivable->amount;

        $rp=new ReceivablePay();
        $rp->receivable_id=$receivable->receivable_id;
        $rp->pay_type=15;
        $rp->tran_no=$tran_no;
        $rp->save();

        if($receivable->type==2){//如果是期初收款
            $ba=BeginArrear::where("shop_id",$receivable->shop_id)->where("company_id",$receivable->company_id)->lockForUpdate()->first(); 
            //记录用户充值 不记录充值记录  只记录流水
            Account::record($user->id,0,3,$tran_no,1,118,$order_amount,'期初收回收入,收回单号:'.$receivable->receivable_id);
            //记录用户支出
            Account::record_base('1',$tran_no,1,118,$order_amount,'期初收回收入,收回单号:'.$receivable->receivable_id);
            $ba->current_amount=$ba->current_amount-$receivable->amount;
            $ba->save();
        }else{          
            //记录用户充值 不记录充值记录  只记录流水
            Account::record($user->id,0,3,$tran_no,1,114,$order_amount,'订单收回收入,收回单号:'.$receivable->receivable_id);
            //记录用户支出
            Account::record_base('1',$tran_no,1,114,$order_amount,'订单收回收入,收回单号:'.$receivable->receivable_id);
        }    
        JournalAccount::where("tran_no",$tran_no)->update(array("created_at"=>$receivable->verify_time)); 
        $receivable->pay_type=15;
        $receivable->tran_no=$tran_no;
        $receivable->save();  
	});
	Log::info("收款单 ：".$receivable->receivable_id." 完毕");
}





